<template>
  <div>
    <el-form inline :model="templateQuery">
      <el-form-item label="关键字">
        <el-input v-model="templateQuery.keyword" placeholder="请输入关键字"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getTemplatePage">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="Plus" @click="templateDialog=true">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="templatePage.list" stripe style="width: 100%">
      <el-table-column prop="id" label="编号" width="180"/>
      <el-table-column prop="type" label="通知类型" width="180"/>
      <el-table-column prop="titleTemplate" label="标题模板"/>
      <el-table-column prop="contentTemplate" label="内容模板"/>
      <el-table-column prop="linkTemplate" label="跳转链接模板"/>
      <el-table-column prop="status" label="启用状态"/>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column prop="updateTime" label="更新时间"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background
                   v-model:current-page="templateQuery.pageNum"
                   v-model:page-size="templateQuery.pageSize"
                   layout="prev, pager, next" :total="templatePage.total"/>

    <el-dialog v-model="templateDialog" title="通知模板" width="500" @close="resetForm">
      <el-form :model="templateForm" ref="templateFormRef" size="large" :rules="rules" label-width="120px" label-position="top">
        <el-form-item label="模板类型" prop="type">
          <el-input v-model="templateForm.type"
                    placeholder="通知类型（与notifications表的type字段一一对应，如follow、comment）"></el-input>
        </el-form-item>
        <el-form-item label="标题模板" prop="titleTemplate">
          <el-input v-model="templateForm.titleTemplate" placeholder="标题模板（可选，如 “新的关注通知”）"></el-input>
        </el-form-item>
        <el-form-item label="内容模板" prop="contentTemplate">
          <el-input v-model="templateForm.contentTemplate"
                    placeholder="内容模板（可选，如 //{{sender_name}} 关注了你，点击查看）"></el-input>
        </el-form-item>
        <el-form-item label="跳转链接模板" prop="linkTemplate">
          <el-input v-model="templateForm.linkTemplate"
                    placeholder="跳转链接模板（可选，如 /user//{{sender_id}}）"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="templateForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="templateDialog = false">取消</el-button>
          <el-button type="primary" @click="templateSubmit(templateFormRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, watch} from "vue";
import {reqCreateTemplate, reqDeleteTemplate, reqGetTemplatePage, reqUpdateTemplate} from "@/api/front/notification";
import type {FormInstance, FormRules} from 'element-plus'
import type {NotificationTemplates} from "@/api/front/notification/type";

/*分页查询相关*/

let templateQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
});
let templatePage = reactive({
  total: 0,
  list: <NotificationTemplates>[],
});
let getTemplatePage = async () => {
  let res = await reqGetTemplatePage(templateQuery)
  Object.assign(templatePage, res.data)
}
watch([() => templateQuery.pageNum, () => templateQuery.pageSize], () => {
  getTemplatePage()
})

/*新增/修改和弹窗相关*/

let templateDialog = ref(false)
let templateForm = reactive<NotificationTemplates>({
  id: "",
  type: "",
  titleTemplate: "",
  contentTemplate: "",
  linkTemplate: "",
  status: 0,
});
let isEditing = ref(false);
let templateFormRef = ref()
let rules = {
  type: [
    {required: true, message: '请选择模板类型', trigger: 'blur'},
  ],
  titleTemplate: [
    {required: true, message: '请输入标题模板', trigger: 'blur'},
  ],
  contentTemplate: [
    {required: true, message: '请输入内容模板', trigger: 'blur'},
  ],
  linkTemplate: [
    {required: true, message: '请输入链接模板', trigger: 'blur'},
  ],
}
let handleEdit = (template) => {
  Object.assign(templateForm, template)
  isEditing.value = true
  templateDialog.value = true
}
let templateSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isEditing.value) {
        await reqUpdateTemplate(templateForm)
      } else await reqCreateTemplate(templateForm)
      await getTemplatePage()
      templateDialog.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}
let resetForm = () => {
  templateForm.id = ''
  templateForm.titleTemplate = ''
  templateForm.contentTemplate = ''
  templateForm.type = ''
  templateForm.status = 0
  templateForm.linkTemplate = ''
  isEditing.value = false
}

/*删除*/
let handleDelete = async (template) => {
  ElMessageBox.confirm(
      `删除之后无法恢复，确定删除${template.type}?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      } as any
  )
      .then(async () => {
        await reqDeleteTemplate(template.id)
        await getTemplatePage()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
      })
}
onMounted(() => {
  getTemplatePage()

})
</script>

<style scoped>

</style>
